<template>
  <!-- 用户管理 -->
  <div class="app-container table-flex-wrapper">
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label="" prop="grade">
        <el-select v-model="queryParams.roleId" placeholder="请选择角色类型" clearable size="small" style="width: 180px"
          @change="handleQuery">
          <el-option v-for="dict in roleOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="keywords">
        <el-input v-model="queryParams.userName" placeholder="模糊搜索用户名" clearable size="small" style="width: 180px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="" prop="keywords">
        <el-input v-model="queryParams.phonenumber" placeholder="模糊搜索手机号" clearable size="small" style="width: 180px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" @click="handleQuery" type="primary">搜索</el-button>
        <el-button size="mini" @click="handleAdd" type="primary">新增</el-button>
        <el-button size="mini" @click="handleBatchDisable" type="primary">批量禁用</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" size="mini" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="70" align="center"></el-table-column>
      <!--<el-table-column prop="avatar" label="头像" align="center"></el-table-column>-->
      <el-table-column prop="userName" label="用户名" align="center"></el-table-column>
      <el-table-column prop="nickName" label="昵称" align="center"></el-table-column>
      <el-table-column prop="roles[0].roleId" label="角色类型" align="center" :formatter="levelFormat"></el-table-column>
      <el-table-column label="用户状态" align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" show-overflow-tooltip  align="center"></el-table-column>
      <el-table-column prop="phonenumber" label="手机号" align="center"></el-table-column>
      <el-table-column prop="operation" label="操作" align="center" min-width="160" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" class="btn" @click="handleUpdate(scope.row)" v-hasPermi="['system:user:edit']">编辑</el-button>
          <el-button size="mini" class="btn" @click="handleResetPwd(scope.row)" v-hasPermi="['system:user:resetPwd']">重置密码</el-button>
          <el-button size="mini" class="btn white" type="primary" @click="deleteInfo(scope.row.userId)" v-hasPermi="['system:user:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" class="d1" v-loading="addAndUpdateLoading">
      <el-form ref="form" :model="form" size="small" :rules="commitRules" label-width="80px">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="form.userName" maxlength="16" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item v-if="form.userId == undefined" label="用户密码" prop="password">
          <el-input v-model="form.password" maxlength="16" placeholder="请输入用户密码" type="password" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入用户昵称" />
        </el-form-item>
        <el-form-item label="角色类型" prop="roleIds[0]">
          <el-select v-model="form.roleIds[0]" placeholder="请选择">
            <el-option v-for="item in rolePopOptions" :key="item.roleId" :label="item.roleName" :value="item.roleId"
              :disabled="item.status == 1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="email" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱地址" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="submitForm('form')">确 定</el-button>
        <el-button @click="cancel" size="small">取 消</el-button>
      </div>
    </el-dialog>

    <resetPwd ref="resetPwd" @submit="resetPwd" ></resetPwd>
  </div>
</template>

<script>
  import { listUser, getUser, addUser, updateUser, resetUserPwd, changeUserStatus, importTemplate, selectedDisable, delUser } from "@/api/system/user";
  import { noRoleList } from "@/api/system/role";
  import { checkStr } from "@/utils/validate.js";
  import resetPwd from "@/layout/components/resetPwd";
  import { encryption } from '@/api/random.js';

  export default {
    name: "management",
    components: {
      resetPwd
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否显示弹出层（数据权限）
        openDataScope: false,
        // 日期范围
        dateRange: [],
        // 状态数据字典
        statusOptions: [],
        //用户表格数据
        userList: [],
        //角色列表
        roleOptions: [],
        //弹框角色列表
        rolePopOptions: [],
        // 部门列表
        deptOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          roleId: '', // 角色类型
          userName: '', // 用户名
          phonenumber: '', // 用户电话
        },
        // 表单参数
        form: {
          userName: "",
          password: "",
          nickName: "",
          email: "",
          phonenumber: "",
          roleIds: []
        },
        defaultProps: {
          children: "children",
          label: "label"
        },
        // 表单校验
        commitRules: {
          userName: [{
            required: true,
            message: "用户名称不能为空",
            trigger: "blur"
          }],
          password: [{
            required: true,
            message: "用户密码不能为空",
            trigger: "blur"
          }, {
            validator(rule, value, callback) {
              if (value && !checkStr(value, "pwd")) {
                callback(new Error("密码必须包含大写字母小写字母和数字，8-20位"));
              } else {
                callback();
              }
            }
          }],
          nickName: [{
            required: true,
            message: "用户昵称不能为空",
            trigger: "blur"
          }],
          phonenumber: [{
            required:true,
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }],
          email: [{
            required:true,
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }],
          "roleIds[0]":[{
            required:true,
            message:"必须选择角色",
            trigger:"blur"
          }]
        },
        // 修改之前的老数据
        updateOddValue: null,
        // 选中要修改的用户
        selectUser: undefined,
        // 新增和修改时发送请求的遮罩层
        addAndUpdateLoading: false,
      };
    },
    created() {
      let self = this;
      noRoleList().then(response => {
        self.roleOptions = [];
        for (var i = 0; i < response.rows.length; ++i) {
          var dict = {
            dictLabel: response.rows[i].roleName,
            dictValue: response.rows[i].roleId
          };
          self.roleOptions.push(dict);
        }
      }).catch((error)=> {
        console.log(error);
      });

      self.getList();

      self.getDicts("sys_normal_disable").then(response => {
        self.statusOptions = response.data;
      }).catch((error)=> {
        console.log(error);
      });
    },
    methods: {
      /**
       * 删除用户管理信息
       * @param id 用户管理id
       */
      deleteInfo(id) {
        let self = this;
         self.$confirm( "确认要删除该条信息吗?", "警告", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
          })
          .then(function() {
            delUser(id).then((res)=>{
              if(res.code==200){
                self.msgSuccess(res.msg);
                self.getList();
              }else{
                self.msgError(res.msg);
              }
            }).catch(()=>{
              self.getList();
            });
          })
          .then(() => {
            self.getList();
          })
          .catch(function(e) {
        });
      },
      /** 查询角色列表 */
      getList() {
        this.loading = true;
        listUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
            this.userList = response.rows;
            this.total = response.total;
            this.loading = false;
          }
        ).catch((error)=> {
          console.log(error);
        });
      },
      levelFormat(row, column) {
        return this.selectDictLabel(this.roleOptions, row.roles[0].roleId);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          userId: undefined,
          deptId: 103,
          userName: undefined,
          nickName: undefined,
          password: undefined,
          phonenumber: undefined,
          email: undefined,
          sex: undefined,
          status: "0",
          remark: undefined,
          postIds: [],
          roleIds: []
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        let self = this;
        console.log(self.queryParams);
        self.getList();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        // this.ids = selection.map(item => item.roleId);
        this.ids = selection.map(item => item.userId);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      /** 新增按钮操作 */
      handleAdd() {
        let self = this;
        self.reset();
        getUser().then(response => {
          this.rolePopOptions = response.roles;
          this.open = true;
          this.title = "添加用户";
          this.form.password = this.initPassword;
        }).catch((error)=> {
          console.log(error);
        });
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        let self = this;
        self.reset();
        const userId = row.userId || self.ids;
        getUser(userId).then(response => {
          self.form = response.data;
          self.rolePopOptions = response.roles;
          self.form.roleIds = response.roleIds;
          self.open = true;
          self.title = "修改用户";

          self.updateOddValue = response.roleIds[0];
        }).catch((error)=> {
          console.log(error);
        });
      },
      /** 重置密码按钮操作 */
      handleResetPwd(row) {
        let self = this;
        self.selectUser = row;
        self.$refs.resetPwd.show('重置密码');
      },
      /** 重置密码 */
      resetPwd(info) {
        let self = this;
        console.log("user", self.selectUser, info);
        let userId = self.selectUser.userId;
        self.$refs.resetPwd.isLoading();
        resetUserPwd( userId, info.oldPassword, info.newPassword, info.confirmPassword ).then(response=>{
          self.$refs.resetPwd.hideResetPwd();
					if (response.code==200) {
						self.msgSuccess("修改成功");
					} else {
						self.msgError(response.msg);
          }
          self.$refs.resetPwd.isNotLoading();
        }).catch((error)=> {
          self.$refs.resetPwd.isNotLoading();
          console.log(error);
        });
			},
      // 用户状态修改
      handleStatusChange(row) {
        let self = this;
        let text = row.status === "0" ? "启用" : "停用";
        self.$confirm( '确认要"' + text + " " + row.userName + " 用户吗?", "警告", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
          })
          .then(function() {
            let data = {"userId":row.userId,"status": row.status};
            console.log(data);
            changeUserStatus(data).then(response => {
              if(response) {
                if (response.code === 200) {
                  self.msgSuccess(response.msg);
                  self.getList();
                } else {
                  self.msgError(response.msg);
                }
              }else{
                if (row.status == "0") {
                  row.status = "1";
                } else {
                  row.status = "0";
                }
              }
            }).catch((error)=> {
              self.msgError(error.msg);
            });;
          })
          .catch(function() {
            if (row.status == "0") {
              row.status = "1";
            } else {
              row.status = "0";
            }
        });
      },
      /** 提交按钮 */
      submitForm(fromInfo) {
        let self = this;
        let newsValue = null;
        self.$refs[fromInfo].validate(valid => {
          if (valid) {
            this.addAndUpdateLoading = true;
            if (this.form.userId != undefined) {
              let oldValue = null;
              for (let index in self.rolePopOptions) {
                if (self.rolePopOptions[index].roleId == self.form.roleIds[0]) {
                  newsValue = self.rolePopOptions[index].roleName;
                }
                if (self.rolePopOptions[index].roleId == self.updateOddValue) {
                  oldValue = self.rolePopOptions[index].roleName;
                }
              }
              console.log(newsValue, oldValue);
              updateUser(this.form, newsValue, oldValue).then(response => {
                if (response.code === 200) {
                  debugger;
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.msgError(response.msg);
                }
                this.addAndUpdateLoading = false;
                window.location.reload()
              }).catch((error)=> {
                console.log(error);
                this.addAndUpdateLoading = false;
              });
            } else {
              self.form.password = encryption(self.form.password).replace("+","$");
              for (let index in self.rolePopOptions) {
                if (self.rolePopOptions[index].roleId == self.form.roleIds[0]) {
                  newsValue = self.rolePopOptions[index].roleName;
                  break;
                }
              }
              console.log(this.form, newsValue);
              addUser(this.form, newsValue).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.msgError(response.msg);
                }
                this.addAndUpdateLoading = false;
              }).catch((error)=> {
                console.log(error);
                this.addAndUpdateLoading = false;
              });
            }
          }
        });
      },
      /** 批量禁用按钮*/
      handleBatchDisable() {
        let self = this;
        console.log(self.ids);
        selectedDisable(self.ids).then(response => {
          console.log(response);
          if(response.code==200) {
            self.msgSuccess(response.msg);
            self.getList();
          }
        }).catch((error)=> {
          console.log(error);
        });
      }
    }
  };
</script>
<style lang="scss" scoped>
  .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
    margin-bottom: 18px!important;
  }
</style>
